package com.libleveldb.implementation

import com.libleveldb.LevelDB
import com.libleveldb.Snapshot
import java.lang.ref.WeakReference

class NativeSnapshot constructor(owner: NativeLevelDB, nsnapshot: Long) : Snapshot() {
    private val owner: WeakReference<LevelDB> = WeakReference(owner)

    @Volatile
    private var nsnapshot: Long
    override val isReleased: Boolean
        get() {
            val owner = owner.get()
            return nsnapshot == 0L || owner == null || owner.isClosed
        }

    fun checkOwner(db: LevelDB): Boolean {
        val owner = owner.get()
        return owner === db
    }

    fun release(): Long {
        val snapshot = nsnapshot

        // nsnapshot may change concurrently here, but only to 0 which we're fine with
        nsnapshot = 0
        return snapshot
    }

    fun id(): Long {
        return nsnapshot
    }

    init {
        this.nsnapshot = nsnapshot
    }
}